const HttpGenerate = require('../okex/http/httpGenerate')
const moment = require('moment');

//延迟
const delay = time => new Promise((s)=>setTimeout(s,time))

//@OrderService
class OkexOrderService {

	//@Value(account.ok_api)
	ok_api;

	//@Autowired
	marketSentimentService;

	//http请求
	http;

	beanInit(){
		const {API_KEY,API_SECRET,API_PASS} = this.ok_api;
		this.http =  HttpGenerate(API_KEY,API_SECRET,API_PASS);
	}


	/**
		instId:BTC-USD-SWAP
		获取币种的最新成交价
	*/
	async getTicker(instId){
		const {last} =  await this.http.getTicker(instId);
		return last;
	}

	/**
	 获取可用余额
	*/
	async getUSDTBalance(){
		const {details:[d]} = await this.http.getAccounts("USDT");
		return d.availEq;
	}

	/**
		市价下单 side => buy sell
	*/
	//@TxLog(title=okexOrder)
	async marketOrder(side,instId,sz){
		return this.http.marketOrder(instId,'cash',side,'market',sz)
	}


	//操作系统分配的订单
	async orderForCoin(orderInfo){

		const {name,amount,fixed} = orderInfo;

		const price  = await this.getTicker(name)
		await delay(500)
		
		const balance = await this.getUSDTBalance()
		await delay(500)

		//余额不足
		if(balance < amount){
			throw(`余额不足.需要:${amount}USDT,okex 账户剩余:${balance}USDT`);
		}

		//获得策略
		const strategy = this.marketSentimentService.getTxStrategy(orderInfo,price)

		const outData = {
			...orderInfo,
			...strategy,
			amount,
			balance:(balance-strategy.realAmount).toFixed(2),
			price,
			date:moment().format('YYYY-MM-DD HH:mm')
		}

		if(strategy.type === 'buy' || strategy.type === 'sell'){
			const {ordId} = await this.marketOrder(strategy.type,name,strategy.size);
			outData.ordId = ordId;
		}

		return outData;
	}


}

module.exports = { OkexOrderService }